package com.idopartx.phonelightning.ui.home.calllightning

import android.content.Context
import android.os.Bundle
import android.text.InputFilter
import android.text.Spanned
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.doAfterTextChanged
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.dotools.umlibrary.UMPostUtils
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.databinding.ActivityEditMorseBinding
import com.idopartx.phonelightning.databinding.DialogExitBinding
import com.idopartx.phonelightning.entity.CallLightningCache
import com.idopartx.phonelightning.entity.CallLightningEntity
import com.idopartx.phonelightning.thread.LightningThread
import com.idopartx.phonelightning.ui.base.BaseActivity
import com.idopartx.phonelightning.ui.filter.MaxTextLengthFilter
import com.idopartx.phonelightning.utils.DialogUtil
import com.idopartx.phonelightning.utils.MorseUtils
import com.idopartx.phonelightning.viewmodel.EditMorseViewModel
import com.tencent.mmkv.MMKV
import com.wuhenzhizao.titlebar.widget.CommonTitleBar

/**
 * 编辑摩斯密码
 */
class EditMorseActivity : BaseActivity<ActivityEditMorseBinding>() {

    companion object {
        const val INTENT_LIGHTNING_VO = Constant.INTENT_LIGHTNING_VO
        const val INTENT_POSITION = Constant.INTENT_POSITION
    }

    private var thread: LightningThread? = null

    private var position = -1

    private val editMorseViewModel: EditMorseViewModel by lazy {
        ViewModelProvider(this).get(EditMorseViewModel::class.java)
    }

    private val callLightningCache: CallLightningCache? by lazy {
        MMKV.defaultMMKV()
            .decodeParcelable(Constant.MMKV_SAVE_CALL_LIGHTNING, CallLightningCache::class.java)
    }

    override fun initLayoutResId(): Int {
        return R.layout.activity_edit_morse
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.viewTitleBar.setListener { v, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_LEFT_BUTTON -> {
                    onBackPressedSupport()
                }
            }
        }
        val callLightningEntity =
            intent?.getParcelableExtra<CallLightningEntity>(INTENT_LIGHTNING_VO)

        position = intent.getIntExtra(INTENT_POSITION, -1)

        editMorseViewModel.titleLiveData.value = if (callLightningEntity != null)
            callLightningEntity.title
        else
            String.format(
                "摩斯电码%d",
                (callLightningCache?.callLightningList?.size ?: 0) + 1
            )

        editMorseViewModel.originLiveData.value = callLightningEntity?.morseOriginTxt

        editMorseViewModel.transLiveData.value = callLightningEntity?.morseTransTxt

        editMorseViewModel.timeLiveData.value = callLightningEntity?.morseTime ?: "0s"

        binding.viewModel = editMorseViewModel
        binding.click = ClickProxy()


        binding.etInputTitle.requestFocus()

        binding.etOrigin.doAfterTextChanged {
            val transTxt = MorseUtils.trans2Morse(binding.etOrigin.text.toString())
            binding.tvTrans.text = transTxt
            binding.tvMorseTime.text = MorseUtils.getMorseTime(transTxt)
        }

        binding.etOrigin.filters = arrayOf(MaxTextLengthFilter(this, 20))

        binding.tvPreview.setOnClickListener {
            thread?.stopThread()
            thread = null
            thread = LightningThread(
                applicationContext,
                MorseUtils.trans2Lightning(binding.tvTrans.text.toString()),
                1
            )
            thread?.start()

        }
    }


    override fun onBackPressedSupport() {
        if (checkEdit()) {
            finish()
        } else {
            val dialogBinding = DataBindingUtil.inflate<DialogExitBinding>(
                LayoutInflater.from(this),
                R.layout.dialog_exit,
                null,
                false
            )
            val dialog = DialogUtil.getDialog(
                this,
                dialogBinding.root,
                DialogUtil.DialogGravity.CENTER
            )

            dialogBinding.tvCancel.setOnClickListener {
                dialog.dismiss()
            }

            dialogBinding.tvConfirm.setOnClickListener {
                ClickProxy().saveAction()
            }

            dialog.show()
        }
    }

    private fun checkEdit(): Boolean {
        if (callLightningCache == null || callLightningCache?.callLightningList.isNullOrEmpty()) {
            return false
        }

        if (callLightningCache?.callLightningList?.get(0)?.title != editMorseViewModel.titleLiveData.value) {
            return false
        }

        if (callLightningCache?.callLightningList?.get(0)?.morseOriginTxt != editMorseViewModel.originLiveData.value) {
            return false
        }

        return true
    }

    inner class ClickProxy {
        fun saveAction() {
            if (TextUtils.isEmpty(editMorseViewModel.titleLiveData.value)) {
                Toast.makeText(this@EditMorseActivity, "请输入标题", Toast.LENGTH_SHORT).show()
                return
            }
            val eventMap = HashMap<String, String>()
            eventMap["text"] = editMorseViewModel.originLiveData.value ?: ""
            UMPostUtils.onEventMap(
                this@EditMorseActivity,
                "call_morse_save_click_parameter_text",
                eventMap
            )


            if (position != -1) {
                callLightningCache?.callLightningList?.get(position)?.apply {
                    title = editMorseViewModel.titleLiveData.value
                    isMorse = true
                    lightNightList = MorseUtils.trans2Lightning(binding.tvTrans.text.toString())
                    morseOriginTxt = editMorseViewModel.originLiveData.value
                    morseTransTxt = binding.tvTrans.text.toString()
                    morseTime = binding.tvMorseTime.text.toString()
                }
            } else {
                val entity = CallLightningEntity(
                    editMorseViewModel.titleLiveData.value,
                    true,
                    MorseUtils.trans2Lightning(binding.tvTrans.text.toString()),
                    editMorseViewModel.originLiveData.value,
                    binding.tvTrans.text.toString(),
                    binding.tvMorseTime.text.toString(),
                )
                callLightningCache?.callLightningList?.add(0, entity)
            }

            MMKV.defaultMMKV().encode(Constant.MMKV_SAVE_CALL_LIGHTNING, callLightningCache)
            finish()
        }
    }

}